<template>
  <div>
    <v-form v-model="valid" ref="myBrandForm">

      <v-text-field label="品牌名称" v-model="brand.name" required :rules="nameRules"></v-text-field>
      <v-text-field label="品牌首字母" v-model="brand.letter" required :rules="letterRules"></v-text-field>

      <v-cascader
        url="/item/category/list"
        multiple
        required
        v-model="brand.categories"
        label="请选择商品分类"/>

      <v-layout row>
        <v-flex xs3>
          <span style="font-size: 16px; color: #444">品牌LOGO：</span>
        </v-flex>
        <v-flex>
          <v-upload
            v-model="brand.image"
            url="/upload/image"
            :multiple="false"
            :pic-width="250"
            :pic-height="90"
          />
        </v-flex>
      </v-layout>

      <v-layout class="my-4" row>
        <v-spacer/>
        <v-btn @click="submit" color="primary">提交</v-btn>
        <v-btn @click="clear">重置</v-btn>
      </v-layout>
    </v-form>

  </div>
</template>

<script>
  export default {
    name: "my-brand-form",
    data() {
      return {
        valid: false, // 表单校验结果标记
        brand: {
          name: '', // 品牌名称
          letter: '', // 品牌首字母
          image: '',// 品牌logo
          categories: [], // 品牌所属的商品分类数组
        },
        nameRules: [
          v => !!v || "品牌名称不能为空",
          v => v.length > 1 || "品牌名称至少2位",
          v => v.length < 8 || "品牌名称最长8位"
        ],
        letterRules: [
          v => !!v || "首字母不能为空",
          v => /^[A-Z]{1}$/.test(v) || "品牌字母只能是A~Z的大写字母"
        ]
      }
    },
    methods: {
      submit() {
        // 1、表单校验
        if (this.$refs.myBrandForm.validate()) {
          let {categories, ...params} = this.brand;

          params.cids = categories.map(c => c.id).join(",");

          this.$http.post("/item/brand",this.$qs.stringify(params))
            .then(()=>{
              this.$emit("close");
            }).catch(()=>{
              alert("终于失败了")
          })
        }
      },
      clear() {
        // 重置表单
        this.$refs.myBrandForm.reset();
        // 需要手动清空商品分类
        this.brand.categories = [];
      }
    }
  }
</script>

<style scoped>

</style>
